
from infra.handler import BaseHandler
from domain.reg.reg_db import create_reg
from domain.reg.reg_db import update_reg_status
from domain.activity.activity_db import get_activity_info
from domain.activity.activity_db import update_activity_info
from domain.reg.reg_db import get_user_regs
from domain.chatroom.chatroom_db import create_chatroom
from domain.message.message_db import insert_message
import json

class UserRegHandler(BaseHandler):
    async def check_and_update_activity_status(self, activity_id, user_id):
        """检查活动是否达到成团人数并更新状态
        
        Args:
            activity_id: 活动ID
            user_id: 当前用户ID
            
        Returns:
            bool: 是否成团
        """
        ret, activity_info = await get_activity_info(activity_id, user_id)
        if not ret:
            return False
        # 检查是否达到成团人数
        if len(activity_info["joiners_ids"]) >= int(activity_info["people_number"]):
              # 创建群聊
            member_list = activity_info["joiners_ids"]
            member_list.append(str(activity_info['created_user_id']))
            chat_success, chat_result = await create_chatroom(
                activity_id=activity_id,
                creator_id=user_id,
                member_list=member_list,
                group_name=activity_info['name'],  # 使用活动名称作为群名
                notification=f"活动时间：{activity_info['start_time']} - {activity_info['end_time']}\n活动地点：{activity_info['address']['name']}"
            )

            if not chat_success:
                self.write(json.dumps({
                    "code": 400,
                    "msg": f"创建群聊失败: {chat_result}"
                }))
                return False
            # 更新活动状态为已开始
            success, _ = await update_activity_info(activity_id, user_id, {'status': 1})
            return success
        return False
    async def get(self):
        """获取用户报名的活动列表
        请求参数：
            page: 页码(可选,默认1)
            page_size: 每页数量(可选,默认10)
            type: 活动类型筛选(可选)
            area: 地区筛选(可选)
            people: 人数筛选(可选)
        返回：
            code: 状态码
            msg: {
                total: 总数
                list: 活动列表
            }
        """
        try:
            user_id, _ = self.get_current_user()
            if not user_id:
                self.write(json.dumps({"code": 404, "msg": "User not found"}))
                return
                
            # 获取分页参数
            page = int(self.get_argument('page', '1'))
            page_size = int(self.get_argument('page_size', '10'))
            
            # 获取筛选参数
            activity_type = self.get_argument('type', None)
            area = self.get_argument('area', None)
            people = self.get_argument('people', None)
            if activity_type == 'all':
                activity_type = None
            if area == 'all':
                area = None
            if people == 'all':
                people = None
            
            # 获取用户报名的活动列表
            ret, reg_info = await get_user_regs(user_id, page, page_size, activity_type, area, people)
            if not ret:
                self.write(json.dumps({"code": 404, "msg": reg_info}))
                return
                
            self.write(json.dumps({
                "code": 200,
                "msg": reg_info
            }))
            return
                
        except Exception as e:
            self.write(json.dumps({"code": 404, "msg": str(e)}))
            return
   
    
    async def post(self):
        try:
            user_id, _ = self.get_current_user()
            if not user_id:
                self.write(json.dumps({"code": 404, "msg": "User not found"}))
                return
            data = json.loads(self.request.body.decode())
            activity_id = data.get("activity_id")
            if not activity_id:
                self.write(json.dumps({"code": 404, "msg": "activity_id is required"}))
                return
            ret, activity_info = await get_activity_info(activity_id, user_id)
            if not ret:
                self.write(json.dumps({"code": 404, "msg": "activity_id is not exist"}))
                return
            if activity_info["status"] != 0:
                self.write(json.dumps({"code": 404, "msg": "activity is not open"}))
                return
            if activity_info["is_registered"] == 0:
                self.write(json.dumps({"code": 404, "msg": "activity is registered"}))
                return
            if activity_info["is_registered"] == 1:
                # 更新数据表
                ret, reg_info = await update_reg_status(user_id, activity_id, 0)
                if not ret:
                    self.write(json.dumps({"code": 404, "msg": reg_info}))
                    return
                # 检查是否达到成团人数
                if await self.check_and_update_activity_status(activity_id, user_id):
                    self.write(json.dumps({"code": 200, "msg": "取消报名成功"}))
                    return
                self.write(json.dumps({"code": 200, "msg": reg_info}))
                return
            if activity_info["is_registered"] == -1:
                ret, reg_info = await create_reg(user_id, activity_id)
                if not ret:
                    self.write(json.dumps({"code": 404, "msg": reg_info}))
                    return
                # 添加报名成功消息
                await insert_message(
                    type="activity",
                    title="报名成功通知",
                    content=f"您已成功报名活动：{activity_info['name']}",
                    receiver_id=user_id,
                    activity_id=activity_id
                )
                # 给活动创建者发送通知
                await insert_message(
                    type="activity",
                    title="新用户报名通知",
                    content=f"有新用户报名了您的活动：{activity_info['name']}",
                    receiver_id=activity_info['created_user_id'],
                    sender_id=user_id,
                    activity_id=activity_id
                )
                # 检查是否达到成团人数
                if await self.check_and_update_activity_status(activity_id, user_id):
                    # 添加成团成功消息
                    for joiner_id in activity_info["joiners_ids"]:
                        await insert_message(
                            type="activity",
                            title="活动成团通知",
                            content=f"活动 {activity_info['name']} 已达到成团人数，群聊已创建",
                            receiver_id=joiner_id,
                            activity_id=activity_id
                        )
                    # 给活动创建者也发送通知
                    await insert_message(
                        type="activity",
                        title="活动成团通知",
                        content=f"您的活动 {activity_info['name']} 已达到成团人数，群聊已创建",
                        receiver_id=activity_info['created_user_id'],
                        activity_id=activity_id
                    )
                    self.write(json.dumps({"code": 200, "msg": "报名成功，活动已成团"}))
                    return
                self.write(json.dumps({"code": 200, "msg": reg_info}))
                return
        except Exception as e:
            self.write(json.dumps({"code": 404, "msg": str(e)}))
            return

    async def delete(self):
        """取消报名
        请求参数：
            activity_id: 活动ID
        返回：
            code: 状态码
            msg: 消息
        """
        try:
            user_id, _ = self.get_current_user()
            if not user_id:
                self.write(json.dumps({"code": 404, "msg": "User not found"}))
                return
                
            data = json.loads(self.request.body.decode())
            activity_id = data.get("activity_id")
            if not activity_id:
                self.write(json.dumps({"code": 404, "msg": "activity_id is required"}))
                return
                
            # 检查活动是否存在
            ret, activity_info = await get_activity_info(activity_id, user_id)
            if not ret:
                self.write(json.dumps({"code": 404, "msg": "activity not found"}))
                return
                
            # 检查是否已报名
            if activity_info["is_registered"] == -1:
                self.write(json.dumps({"code": 404, "msg": "未报名该活动"}))
                return
                
            # 更新报名状态为取消（status=1）
            ret, msg = await update_reg_status(user_id, activity_id, 1)
            if not ret:
                self.write(json.dumps({"code": 404, "msg": msg}))
                return
              # 添加取消报名消息
            await insert_message(
                type="activity",
                title="取消报名通知",
                content=f"您已成功取消报名活动：{activity_info['name']}",
                receiver_id=user_id,
                activity_id=activity_id
            )
            
            # 给活动创建者发送通知
            await insert_message(
                type="activity",
                title="用户取消报名通知",
                content=f"有用户取消报名了您的活动：{activity_info['name']}",
                receiver_id=activity_info['created_user_id'],
                sender_id=user_id,
                activity_id=activity_id
            )
              # 从活动的参与者列表中移除当前用户
            joiners_ids = activity_info["joiners_ids"]
            if user_id in joiners_ids:
                joiners_ids.remove(user_id)
                # 更新活动信息
                await update_activity_info(activity_id, user_id, {
                    "joiners_ids": joiners_ids
                })
            self.write(json.dumps({"code": 200, "msg": "取消报名成功"}))
            return
                
        except Exception as e:
            self.write(json.dumps({"code": 404, "msg": str(e)}))
            return